package ch.usi.inf.pf2.cell;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * A TokenRecognizer can recognize tokens of a specific type, using a regular expression.
 * It can determine whether at a specific position in a given text string,
 * there is a token it recognizes.

 * @author Matthias.Hauswirth@unisi.ch
 */
public final class TokenRecognizer {

	private final TokenType tokenType;
	private final Pattern pattern;
	private Matcher matcher;
	private int currentPosition;
	
	
	public TokenRecognizer(final TokenType tokenType, final String regex) {
		this.tokenType = tokenType;
		pattern = Pattern.compile(regex);
	}
	
	public void setText(final String text) {
		matcher = pattern.matcher(text);
	}

	public boolean find(final int currentPosition) {
		this.currentPosition = currentPosition;
		if (matcher.find(currentPosition)) {
			final int start = matcher.start();
			if (start==currentPosition) {
				return true;
			}
		}
		return false; 
	}

	public int getTokenLength() {
		final String match = matcher.group();
		return match.length();
	}

	public Token getToken() {
		final String match = matcher.group();
		return new Token(tokenType, match, currentPosition);
	}

}
